package com.alibaba.citrus.cr.platform.enhance.facade.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerRepository;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.crplatformenhance.api.customerquery.service.CustomerQueryService;
import com.epoch.app.crplatformenhance.domain.customer.service.CustomerService;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryResponse;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.crplatformenhance.dto.request.CustomerBatchRequest;
import com.epoch.app.crplatformenhance.dto.request.CustomerRequest;
import com.epoch.app.crplatformenhance.dto.request.QueryCustomerRequest;
import com.epoch.app.crplatformenhance.model.dto.PageQueryCustomerRequest;
import com.epoch.app.crplatformenhance.opecustomerindex.model.OpeCustomerIndex;
import com.epoch.app.crplatformenhance.sdo.CustomerSDO;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

@Primary
@Service
public class CustomerQueryServiceImpl implements CustomerQueryService {

    @Resource
    private CustomerRepository customerRepository;
    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerAddressService customerAddressService;

    @Override
    @FacadeInvoker
    public Result<CustomerSDO> queryCustomer(CustomerRequest customerRequest) {
        CustomerSDO result = customerRepository.query(customerRequest);
        return Result.success(result);
    }

    @Override
    @FacadeInvoker
    public Result<List<CustomerSDO>> batchQueryCustomer(CustomerBatchRequest request) {
        List<CustomerSDO> response = customerRepository.batchQuery(request);
        return Result.success(response);
    }

    @Override
    @FacadeInvoker
    public Result<List<CustomerSDO>> pageQueryCustomer(QueryCustomerRequest request) {
        PageResult<List<CustomerSDO>> customerList = customerRepository.pageQuery(request);
        return Result.listSuccess(customerList.getContent(), customerList.getTotal());
    }

    @Override
    public Result<List<OpeCustomerIndex>> pageQueryCustomerByEsDegrade(
        PageQueryCustomerRequest pageQueryCustomerRequest) {
        Result<List<OpeCustomerIndex>> customerResp = customerService.pageQueryCustomerByEsDegrade(
            pageQueryCustomerRequest);
        if (CollectionUtils.isNotEmpty(customerResp.getResult())) {
            List<String> codes = new ArrayList<>();
            customerResp.getResult().stream().forEach(x -> codes.add(x.getCode()));
            List<List<String>> partCodes = new ArrayList<>();
            partCodes = Lists.partition(codes, 500);
            Map<String, List<CustomerAddress>> addressMap = new HashMap<>();
            for (List<String> childPartCodes : partCodes) {
                BatchQueryRequest batchQueryRequest = new BatchQueryRequest();
                batchQueryRequest.setAddressCodes(childPartCodes);
                BatchQueryResponse addressResult = customerAddressService.batchQuery(batchQueryRequest);
                if (CollectionUtils.isNotEmpty(addressResult.getResult())) {
                    addressResult.getResult().stream().forEach(x -> {
                        if (addressMap.containsKey(x.getAddressCode())) {
                           addressMap.get(x.getAddressCode()).add(x);
                        } else {
                            List<CustomerAddress> addresses = new ArrayList<>();
                            addresses.add(x);
                            addressMap.put(x.getAddressCode(), addresses);
                        }
                    });
                }
            }
            customerResp.getResult().stream().forEach(x -> {
                String addressKey = x.getCode();
                List<CustomerAddress> addresses = addressMap.get(addressKey);
                if(CollectionUtils.isNotEmpty(addresses)) {
                    List<String> orgSaleDepartmentCodeList = new ArrayList<>();
                    List<String> salesAreaList = new ArrayList<>();
                    List<String> orgSaleOrganizationCodeList = new ArrayList<>();
                    List<String> channelCodeList = new ArrayList<>();
                    List<String> orgSaleChannelCodeList = new ArrayList<>();
                    List<String> orgBussinessUnitCodeList = new ArrayList<>();
                    for (CustomerAddress childAdress : addresses) {
                        orgSaleDepartmentCodeList.add(childAdress.getOrgSaleDepartmentCode());
                        salesAreaList.add(childAdress.getSalesArea());
                        orgSaleOrganizationCodeList.add(childAdress.getOrgSaleOrganizationCode());
                        channelCodeList.add(childAdress.getChannelCode());
                        orgSaleChannelCodeList.add(childAdress.getOrgSaleChannelCode());
                        orgBussinessUnitCodeList.add(childAdress.getOrgBussinessUnitCode());
                    }
                    x.setOrgSaleDepartmentCodeList(orgSaleDepartmentCodeList);
                    x.setSalesAreaList(salesAreaList);
                    x.setOrgSaleOrganizationCodeList(orgSaleOrganizationCodeList);
                    x.setChannelCodeList(channelCodeList);
                    x.setOrgSaleChannelCodeList(orgSaleChannelCodeList);
                    x.setOrgBussinessUnitCodeList(orgBussinessUnitCodeList);
                }
            });
        }
        return customerResp;
    }
}
